import { Row, Col, Select, PageHeader, Input, Button, Table, Tag, Space, Form, Divider, Popconfirm, message, Pagination } from "antd";
import axios from "axios";
import { useEffect, useState } from "react";
import { Link, useNavigate } from 'react-router-dom';

const { Option } = Select;

const BUSINESS_TYPE = new Map([
  ["DINNER", "正餐"],
  ["FAST_FOOD", "快餐"],
  ["HOT_POT", "火锅"],
  ["BARBECUE", "烧烤"],
  ["WESTERN_FOOD", "西餐"],
]);
const MANAGEMENT_TYPE = new Map([
  ["DIRECT_SALES", "直营"],
  ["ALLIANCE", "加盟"],
]);


export default function Shop() {
  const [status, setStatus] = useState();
  const [data, setData] = useState([]);
  const [totalCount, setTotalCount] = useState();
  const [pageCondition, setPageCondition] = useState({});
  const [currentPage, setCurrentPage] = useState();
  const [queryCondition, setQueryCondition] = useState({});
  const navigate = useNavigate();
  const [form] = Form.useForm();
  useEffect(() => {
    queryShop({}, {});
  }, []);

  function queryShop(queryCondition, pageCondition) {
    const instance = axios.create({
      headers: { "tenantId": 500, "userId": 11000 }
    })
    const request = {
      "businessType": queryCondition.businessType,
      "enabled": queryCondition.enabled,
      "keyword": queryCondition.keyword,
      "managementType": queryCondition.managementType,
      "pageIndex": pageCondition.pageIndex,
      "pageSize": pageCondition.pageSize,
    }
    instance.post('/shop/search',
      request
    )
      .then((res) => {
        if (res.data.status.code === 0) {
          setData([res.data.data.records]);
          setTotalCount(res.data.data.totalCount);
          setCurrentPage(res.data.data.pageIndex)
        }
      })
  }

  const onFinish = (values) => {
    console.log(values)
    const queryCondition = {
      "keyword": values.keyword,
      "businessType": values.businessType,
      "managementType": values.managementType,
      "enabled": values.enabled
    }
    setQueryCondition(queryCondition);
    queryShop(queryCondition, pageCondition);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const onInputChange = (value) => {
    if (value.target.value === '') {
      queryShop(queryCondition, pageCondition);
    }
  };

  const closeOrOpenShop = (value) => {
    console.log(value)
    if (value.enabled) {
      const instance = axios.create({
        headers: { "tenantId": value.tenantId, "userId": value.auditing.createdBy }
      })
      instance.post('/shop/' + value.businessNo + '/close', {
        "version": value.version
      })
        .then((res) => {
          queryShop(queryCondition, pageCondition);
        })
      return;
    }

    const instance = axios.create({
      headers: { "tenantId": value.tenantId, "userId": value.auditing.createdBy }
    })
    instance.post('/shop/' + value.businessNo + '/open', {
      "version": value.version
    })
      .then((res) => {
        queryShop(queryCondition, pageCondition);
      })
  };

  const onPageChange = (pageIndex, pageSize) => {
    const pageCondition = {
      "pageIndex": (pageIndex === 1) ? pageIndex : (pageIndex - 1) * 10,
      "pageSize": pageSize * pageIndex
    }
    setPageCondition(pageCondition);
    queryShop(queryCondition, pageCondition);
  }

  function confirm(e) {
    message.success('操作成功！');
    closeOrOpenShop(status);
  };
  const onReset = () => {
    queryShop({}, {});
  }

  function cancel(e) {
    console.log(e);
  };
  const columns = [
    {
      title: '营业状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: enabled => <Tag>{enabled ? '营业中' : '停业中'}</Tag>,
    },
    {
      title: '门店名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '主营业态',
      dataIndex: 'businessType',
      key: 'businessType',
      render: (businessType) => <>{BUSINESS_TYPE.get(businessType)}</>
    },
    {
      title: '管理类型',
      key: 'managementType',
      dataIndex: 'managementType',
      render: (managementType) => <>{MANAGEMENT_TYPE.get(managementType)}</>
    },
    {
      title: '营业时间',
      key: 'openingHours',
      dataIndex: 'openingHours',
      render: openingHours => (
        <>
          {openingHours.openTime + '~' + openingHours.closeTime}
        </>
      ),
    },
    {
      title: '营业面积',
      key: 'businessArea',
      dataIndex: 'businessArea',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <>
          <Space size="middle">
            <Button
              className="edit-btn"
              onClick={() => {
                navigate('/editShop', { state: { data: text }, replace: true });
              }}>
              <Link to={'/editShop'}>编辑</Link>
            </Button>|
            <Popconfirm
              title={text.enabled ? "请确认是否需要停用该门店？" : "请确认是否需要启用该门店？"}
              onConfirm={confirm}
              onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Button
                className="edit-btn"
                onClick={() => {
                  setStatus(text);
                }}
              >
                {text.enabled ? "停用" : "开启"}
              </Button>
            </Popconfirm>
          </Space>
        </>
      ),
    },
  ];
  console.log(totalCount)
  return (
    <>
      <Row className="title-row" >
        <Col span={18}>
          <PageHeader
            className="site-page-header"
            title="门店管理"
            subTitle=""
          />
        </Col>
      </Row>
      <Form
        form={form}
        name="searchCondition"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={(value) => {
          onFinish(value)
          // setQueryCondition(value);
        }}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Row gutter={[16, 12]}>
          <Col style={{ "width": "32px" }}>
            <Divider><span className="span-shop-address">营业状态</span></Divider>
          </Col>
          <Col span={6}>
            <Form.Item
              name="enabled"
            >
              <Select
                defaultValue="所有"
                style={{
                  "width": "180px",
                  "marginLeft": "81px",
                  "borderLeft": "none"
                }}
              >
                <Option>所有</Option>
                <Option value="true">营业中</Option>
                <Option value="false">停业中</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col style={{ "width": "32px" }}>
            <Divider><span className="span-shop-address">主营业态</span></Divider>
          </Col>
          <Col span={6}>
            <Form.Item
              name="businessType"
            >
              <Select
                defaultValue="所有"
                style={{
                  "width": "180px",
                  "marginLeft": "81px",
                  "borderLeft": "none"
                }}
              >
                <Option>所有</Option>
                <Option value="DINNER">正餐</Option>
                <Option value="FAST_FOOD">快餐</Option>
                <Option value="HOT_POT">火锅</Option>
                <Option value="BARBECUE">烧烤</Option>
                <Option value="WESTERN_FOOD">西餐</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col style={{ "width": "32px" }}>
            <Divider><span className="span-shop-address">管理类型</span></Divider>
          </Col>
          <Col span={8}>
            <Form.Item
              name="managementType"
            >
              <Select
                defaultValue="所有"
                style={{
                  "width": "180px",
                  "marginLeft": "80px",
                  "borderLeft": "none"
                }}
              >
                <Option>所有</Option>
                <Option value="DIRECT_SALES">直营</Option>
                <Option value="ALLIANCE">加盟</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={6}>
            <Form.Item
              name="keyword"
            >
              <Input
                onChange={onInputChange}
                placeholder="请输入门店名"
                style={{ width: 340 }}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
            >
              <Button
                htmlType="submit"
                style={{
                  "backgroundColor": "rgb(244,188,72)",
                  "width": "160px"
                }}
              >
                查询
              </Button>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
            >
              <Button
                htmlType="reset"
                onClick={onReset}
              >
                重置
              </Button>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Button>
              <Link to={'/createShop'}>创建新门店</Link>
            </Button>
          </Col>
        </Row>
      </Form>
      <Row>
        <Col span={24}>
          <Table
            columns={columns}
            dataSource={data[0]}
            scroll={{ y: '350px' }}
            pagination={false}
          />
        </Col>

        <Pagination
          total={totalCount}
          current={currentPage}
          showQuickJumper
          showSizeChanger
          style={{
            "marginTop": "10px"
          }}
          onChange={onPageChange}
        />
      </Row>
    </>
  );
}